<template>
  <div class="page-main">
    <query-page
      ref="queryPageRef"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      :has-line="false"
      title="采购计划综合查询"
      row-selection-type="checkbox"
      @selection-change="selectionChange"
      @query-data="getData"
    >
      <template #top-container>
        <p-tabs
          v-model:value="activeTab"
          :is-show-num="false"
          :tab-list="materialType"
          @change="handleChange"
        ></p-tabs>
      </template>
      <!-- 制单状态（0-编制中，1-待审批，2-审批中，3-审批通过，4 -拒绝 5-商务经理接收）-->
      <template #businessStatusName="{ record }">
        <div
          :class="{
            red: record.businessStatus === 4,
            green: record.businessStatus === 3,
            yellow: [0, 1, 2, 5].includes(record.businessStatus),
          }"
        >
          <span class="dot"></span>
          {{ record.businessStatusName }}
        </div>
      </template>
      <template #rejectReason="{ record }">
        <div class="reject-reason">{{ record.rejectReason }}</div>
      </template>
      <template #container-side>
        <a-space>
          <a-button
            v-permission="['procurement:plan-list:export']"
            @click="ExeclExport"
            >Excel导出</a-button
          >
        </a-space>
      </template>
    </query-page>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue';

  import queryPage from '@/common/components/query-page/index.vue';
  // import { Modal } from '@arco-design/web-vue';

  import {
    formRenderConfig,
    formComponentConfig,
  } from '@/views/purchase-plan/components/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '@/views/purchase-plan/components/tableComp/baseTableConfig';
  import { baseRenderKeys } from '@/views/purchase-plan/components/baseDataReceive';
  import {
    getPlanListPage,
    purchasePlanExport,
  } from '@/api/purchase-plan/planAuthorized';
  import { Message } from '@arco-design/web-vue';
  import { downFileToExcel } from '@/common/utils/downFile';

  // import PageTitle from '@/common/components/title/page-title.vue';
  import { materialType } from '@/config/const';
  import PTabs from '../components/p-tabs.vue';

  // 物料类型代码( 1标准件 2 成品 3原材料 4 零组件 5锻铸件)

  const queryPageRef = ref();

  // tab 头部切换change
  const handleChange = async (val) => {
    activeTab.value = val;
    selectedKeys.value = [];
    initData();
    await nextTick(() => {
      queryPageRef.value.setCurrent(1);
      getData();
    });
  };

  const selectedKeys = ref([]);
  const activeTab = ref('2');
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  const total = ref(0);

  const selection = ref<any[]>([]);
  // 渲染检索项
  const formRenderKeys = ref<any[]>([]);
  // 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([]);
  // 传递给后台的字段
  const deliveryInfo = ref({
    form: {},
  });
  //  表头数据
  interface Tst {
    [index: string]: any;
  }
  // 物料类型代码( 1标准件 2 成品 3原材料 4 零组件 5锻铸件)
  const dataRenderBase = ref<Tst>({
    '2': baseRenderKeys.finishedProduct.formRenderKeys,
    '3': baseRenderKeys.rawMaterial.formRenderKeys,
    '1': baseRenderKeys.standardPart.formRenderKeys,
    '4': baseRenderKeys.zeroCom.formRenderKeys,
    '5': baseRenderKeys.forgingAndCasting.formRenderKeys,
  });
  // 物料类型代码( 1标准件 2 成品 3原材料 4 零组件 5锻铸件)
  // 表格数据
  const dataRenderBase2 = ref<Tst>({
    '2': baseRenderKeys.finishedProduct.newTableRenderKeys,
    '3': baseRenderKeys.rawMaterial.newTableRenderKeys,
    '1': baseRenderKeys.standardPart.newTableRenderKeys,
    '4': baseRenderKeys.zeroCom.newTableRenderKeys,
    '5': baseRenderKeys.forgingAndCasting.newTableRenderKeys,
  });
  // 获取筛选form的renderKey(表单渲染项)
  formRenderKeys.value = dataRenderBase.value[activeTab.value];
  tableRenderKeys.value = dataRenderBase2.value[activeTab.value];
  // 表单选中的数据
  // let selectList = reactive<string[]>([]);
  const selectionChange = (val: string[]) => {
    console.log(val, 'valvalvalval');
    // selectList = val;
    selection.value = renderData.value.filter((item) => {
      console.log(item, 'item++++++++++++');
      return val.includes(item.id);
    });
  };
  const getData = async (queryInfo: object) => {
    if (!queryInfo) {
      queryInfo = queryPageRef.value.getStatus();
    }
    renderData.value = [];
    isLoading.value = true;
    console.log('queryInfo', queryInfo);
    deliveryInfo.value.form = { ...queryInfo };
    // 物料类型代码( 1标准件 2 成品 3原材料 4 零组件 5锻铸件)

    try {
      const res = (await getPlanListPage({
        mdsItemType: activeTab.value,
        beginExecutionStatus: 5,
        ...queryInfo,
      })) as any;
      console.log(res, 'res+++++++++++++');
      if (res.code === 200) {
        total.value = res.data.total;
        renderData.value = res.data.list;
      }
    } finally {
      isLoading.value = false;
    }
  };
  // 初期话
  const initData = () => {
    // 获取筛选form的renderKey(表单渲染项)
    formRenderKeys.value = dataRenderBase.value[activeTab.value];
    tableRenderKeys.value = [...dataRenderBase2.value[activeTab.value]];
  };
  const ExeclExport = async () => {
    const params = {
      ...deliveryInfo.value.form,
      mdsItemType: activeTab.value,
      beginExecutionStatus: 5,
    };
    console.log(params, 'paramsparams');
    console.log(deliveryInfo.value.form, 'deliveryInfo.value.form');

    try {
      const { data, fileName }: any = await purchasePlanExport(params);
      downFileToExcel(fileName, data);
    } catch (error) {
      Message.error(`导出异常!${error}`);
    } finally {
      isLoading.value = false;
    }
  };

  onMounted(() => {
    initData();
  });
</script>

<style lang="less" scoped>
  .plan-synthesize-receive-container {
    height: calc(100% - 32px);
    margin: 16px;
    padding: 12px 24px;
    background-color: #fff;
    border-radius: 8px;
  }
  .reject-reason {
    color: #d40000;
  }
  .red {
    color: #d40000;
    .dot {
      background-color: #d40000;
    }
  }

  .green {
    color: #2ca340;
    .dot {
      background-color: #2ca340;
    }
  }

  .yellow {
    color: #c78b00;
    .dot {
      background-color: #c78b00;
    }
  }
  .dot {
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 4px;
    margin-right: 2px;
  }
</style>
